using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using EIMS.Data;
using EIMS.Models;
using EIMS.Models.Enums;
using EIMS.Models.ViewModels;
using System.Security.Claims;
using System.ComponentModel.DataAnnotations;

namespace EIMS.Controllers
{
    [Authorize]
    public class SupplierController : Controller
    {
        private readonly ApplicationDbContext _context;

        public SupplierController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Supplier
        public async Task<IActionResult> Index(string searchString, SupplierType? type, SupplierStatus? status)
        {
            var suppliersQuery = _context.Suppliers.AsQueryable();

            // 搜索过滤
            if (!string.IsNullOrEmpty(searchString))
            {
                suppliersQuery = suppliersQuery.Where(s => 
                    s.Name.Contains(searchString) || 
                    s.SupplierNumber.Contains(searchString) ||
                    s.ContactPerson.Contains(searchString) ||
                    s.PhoneNumber.Contains(searchString) ||
                    s.Email.Contains(searchString)
                );
            }

            // 类型过滤
            if (type.HasValue)
            {
                suppliersQuery = suppliersQuery.Where(s => s.Type == type);
            }

            // 状态过滤
            if (status.HasValue)
            {
                suppliersQuery = suppliersQuery.Where(s => s.Status == status);
            }

            // 将枚举转换为下拉列表选项
            ViewBag.TypeList = Enum.GetValues(typeof(SupplierType))
                .Cast<SupplierType>()
                .Select(t => new SelectListItem
                {
                    Value = ((int)t).ToString(),
                    Text = GetEnumDisplayName(t),
                    Selected = type.HasValue && type.Value == t
                })
                .ToList();

            ViewBag.StatusList = Enum.GetValues(typeof(SupplierStatus))
                .Cast<SupplierStatus>()
                .Select(s => new SelectListItem
                {
                    Value = ((int)s).ToString(),
                    Text = GetEnumDisplayName(s),
                    Selected = status.HasValue && status.Value == s
                })
                .ToList();

            // 把搜索条件放入ViewBag用于视图中保留搜索条件
            ViewBag.SearchString = searchString;
            ViewBag.Type = type;
            ViewBag.Status = status;

            return View(await suppliersQuery.ToListAsync());
        }

        // GET: Supplier/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var supplier = await _context.Suppliers
                .FirstOrDefaultAsync(s => s.Id == id);

            if (supplier == null)
            {
                return NotFound();
            }

            // 创建供应商详情视图模型
            var viewModel = new SupplierDetailViewModel
            {
                Supplier = supplier,
                Contacts = await _context.SupplierContacts
                    .Where(c => c.SupplierId == id)
                    .ToListAsync(),
                Transactions = await _context.SupplierTransactions
                    .Where(t => t.SupplierId == id)
                    .ToListAsync()
            };

            // 计算统计数据
            viewModel.TransactionCount = viewModel.Transactions.Count();
            viewModel.TotalTransactionAmount = viewModel.Transactions.Sum(t => t.Amount);
            viewModel.UnpaidAmount = viewModel.Transactions
                .Where(t => t.PaymentStatus != Models.Enums.PaymentStatus.Paid)
                .Sum(t => t.Amount);

            return View(viewModel);
        }

        // GET: Supplier/Create
        [Authorize(Roles = "Administrator,Manager")]
        public IActionResult Create()
        {
            ViewBag.Types = new SelectList(Enum.GetValues(typeof(SupplierType))
                .Cast<SupplierType>()
                .Select(t => new { Id = (int)t, Name = GetEnumDisplayName(t) }),
                "Id", "Name");
                
            ViewBag.CreditRatings = new SelectList(Enum.GetValues(typeof(CreditRating))
                .Cast<CreditRating>()
                .Select(r => new { Id = (int)r, Name = GetEnumDisplayName(r) }),
                "Id", "Name");
                
            ViewBag.Statuses = new SelectList(Enum.GetValues(typeof(SupplierStatus))
                .Cast<SupplierStatus>()
                .Select(s => new { Id = (int)s, Name = GetEnumDisplayName(s) }),
                "Id", "Name");
                
            return View();
        }

        // POST: Supplier/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Create([Bind("Id,SupplierNumber,Name,Type,CreditRating,ContactPerson,PhoneNumber,Email,Address,Fax,Website,BankAccount,BankName,TaxNumber,Remarks,Status")] Supplier supplier)
        {
            if (ModelState.IsValid)
            {
                // 检查供应商编号是否已存在
                bool exists = await _context.Suppliers.AnyAsync(s => s.SupplierNumber == supplier.SupplierNumber);
                if (exists)
                {
                    ModelState.AddModelError("SupplierNumber", "该供应商编号已存在");
                    PrepareViewBags();
                    return View(supplier);
                }

                // 设置创建时间
                supplier.CreatedAt = DateTime.Now;
                
                _context.Add(supplier);
                await _context.SaveChangesAsync();
                
                TempData["SuccessMessage"] = "供应商添加成功！";
                return RedirectToAction(nameof(Index));
            }
            
            PrepareViewBags();
            return View(supplier);
        }

        // GET: Supplier/Edit/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var supplier = await _context.Suppliers.FindAsync(id);
            if (supplier == null)
            {
                return NotFound();
            }
            
            PrepareViewBags();
            return View(supplier);
        }

        // POST: Supplier/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> Edit(int id, [Bind("Id,SupplierNumber,Name,Type,CreditRating,ContactPerson,PhoneNumber,Email,Address,Fax,Website,BankAccount,BankName,TaxNumber,Remarks,Status,CreatedAt")] Supplier supplier)
        {
            if (id != supplier.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // 检查供应商编号是否已被其他供应商使用
                    var existingSupplier = await _context.Suppliers
                        .FirstOrDefaultAsync(s => s.SupplierNumber == supplier.SupplierNumber && s.Id != supplier.Id);
                    if (existingSupplier != null)
                    {
                        ModelState.AddModelError("SupplierNumber", "该供应商编号已被其他供应商使用");
                        PrepareViewBags();
                        return View(supplier);
                    }

                    // 更新时间
                    supplier.UpdatedAt = DateTime.Now;
                    
                    _context.Update(supplier);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SupplierExists(supplier.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                TempData["SuccessMessage"] = "供应商信息已更新！";
                return RedirectToAction(nameof(Index));
            }
            PrepareViewBags();
            return View(supplier);
        }

        // GET: Supplier/Delete/5
        [Authorize(Roles = "Administrator")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var supplier = await _context.Suppliers
                .FirstOrDefaultAsync(s => s.Id == id);
                
            if (supplier == null)
            {
                return NotFound();
            }

            return View(supplier);
        }

        // POST: Supplier/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator")]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var supplier = await _context.Suppliers.FindAsync(id);
            if (supplier != null)
            {
                _context.Suppliers.Remove(supplier);
            }
            
            await _context.SaveChangesAsync();
            TempData["SuccessMessage"] = "供应商已删除！";
            return RedirectToAction(nameof(Index));
        }

        private bool SupplierExists(int id)
        {
            return _context.Suppliers.Any(e => e.Id == id);
        }

        private void PrepareViewBags()
        {
            ViewBag.Types = new SelectList(Enum.GetValues(typeof(SupplierType))
                .Cast<SupplierType>()
                .Select(t => new { Id = (int)t, Name = GetEnumDisplayName(t) }),
                "Id", "Name");
                
            ViewBag.CreditRatings = new SelectList(Enum.GetValues(typeof(CreditRating))
                .Cast<CreditRating>()
                .Select(r => new { Id = (int)r, Name = GetEnumDisplayName(r) }),
                "Id", "Name");
                
            ViewBag.Statuses = new SelectList(Enum.GetValues(typeof(SupplierStatus))
                .Cast<SupplierStatus>()
                .Select(s => new { Id = (int)s, Name = GetEnumDisplayName(s) }),
                "Id", "Name");
        }

        // GET: Supplier/AddContact/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddContact(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var supplier = await _context.Suppliers.FindAsync(id);
            if (supplier == null)
            {
                return NotFound();
            }
            
            var viewModel = new SupplierContactViewModel
            {
                SupplierId = supplier.Id,
                SupplierName = supplier.Name
            };
            
            return View(viewModel);
        }

        // POST: Supplier/AddContact
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddContact(SupplierContactViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var supplier = await _context.Suppliers.FindAsync(viewModel.SupplierId);
                    if (supplier == null)
                    {
                        return NotFound();
                    }

                    var supplierContact = new SupplierContact
                    {
                        SupplierId = viewModel.SupplierId,
                        Name = viewModel.Name,
                        Position = viewModel.Position,
                        PhoneNumber = viewModel.PhoneNumber,
                        Email = viewModel.Email,
                        IsDefault = viewModel.IsDefault,
                        Remarks = viewModel.Remarks,
                        CreatedAt = DateTime.Now
                    };

                    // 如果设置为默认联系人，则取消其他默认联系人
                    if (viewModel.IsDefault)
                    {
                        var defaultContacts = await _context.SupplierContacts
                            .Where(c => c.SupplierId == viewModel.SupplierId && c.IsDefault)
                            .ToListAsync();
                            
                        foreach (var contact in defaultContacts)
                        {
                            contact.IsDefault = false;
                            _context.Update(contact);
                        }
                    }
                    
                    _context.Add(supplierContact);
                    await _context.SaveChangesAsync();
                    
                    TempData["SuccessMessage"] = "联系人添加成功！";
                    return RedirectToAction(nameof(Details), new { id = viewModel.SupplierId });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, $"添加联系人失败: {ex.Message}");
                }
            }
            
            var supplierInfo = await _context.Suppliers.FindAsync(viewModel.SupplierId);
            if (supplierInfo != null)
            {
                viewModel.SupplierName = supplierInfo.Name;
            }
            
            return View(viewModel);
        }

        // GET: Supplier/EditContact/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditContact(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contact = await _context.SupplierContacts
                .Include(c => c.Supplier)
                .FirstOrDefaultAsync(c => c.Id == id);
                
            if (contact == null)
            {
                return NotFound();
            }
            
            var viewModel = new SupplierContactViewModel
            {
                Id = contact.Id,
                SupplierId = contact.SupplierId,
                SupplierName = contact.Supplier.Name,
                Name = contact.Name,
                Position = contact.Position,
                PhoneNumber = contact.PhoneNumber,
                Email = contact.Email,
                IsDefault = contact.IsDefault,
                Remarks = contact.Remarks
            };
            
            return View(viewModel);
        }

        // POST: Supplier/EditContact/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditContact(int id, SupplierContactViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var contact = await _context.SupplierContacts.FindAsync(id);
                    if (contact == null)
                    {
                        return NotFound();
                    }

                    // 更新联系人信息
                    contact.Name = viewModel.Name;
                    contact.Position = viewModel.Position;
                    contact.PhoneNumber = viewModel.PhoneNumber;
                    contact.Email = viewModel.Email;
                    contact.IsDefault = viewModel.IsDefault;
                    contact.Remarks = viewModel.Remarks;
                    contact.UpdatedAt = DateTime.Now;
                    
                    // 如果设置为默认联系人，则取消其他默认联系人
                    if (viewModel.IsDefault)
                    {
                        var defaultContacts = await _context.SupplierContacts
                            .Where(c => c.SupplierId == contact.SupplierId && c.Id != contact.Id && c.IsDefault)
                            .ToListAsync();
                            
                        foreach (var defaultContact in defaultContacts)
                        {
                            defaultContact.IsDefault = false;
                            _context.Update(defaultContact);
                        }
                    }
                    
                    _context.Update(contact);
                    await _context.SaveChangesAsync();
                    
                    TempData["SuccessMessage"] = "联系人信息更新成功！";
                    return RedirectToAction(nameof(Details), new { id = contact.SupplierId });
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SupplierContactExists(viewModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            
            var supplierInfo = await _context.Suppliers.FindAsync(viewModel.SupplierId);
            if (supplierInfo != null)
            {
                viewModel.SupplierName = supplierInfo.Name;
            }
            
            return View(viewModel);
        }

        // GET: Supplier/DeleteContact/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteContact(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contact = await _context.SupplierContacts
                .Include(c => c.Supplier)
                .FirstOrDefaultAsync(c => c.Id == id);
                
            if (contact == null)
            {
                return NotFound();
            }

            return View(contact);
        }

        // POST: Supplier/DeleteContact/5
        [HttpPost, ActionName("DeleteContact")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteContactConfirmed(int id)
        {
            var contact = await _context.SupplierContacts.FindAsync(id);
            if (contact != null)
            {
                int supplierId = contact.SupplierId;
                _context.SupplierContacts.Remove(contact);
                await _context.SaveChangesAsync();
                
                TempData["SuccessMessage"] = "联系人已删除！";
                return RedirectToAction(nameof(Details), new { id = supplierId });
            }
            
            return RedirectToAction(nameof(Index));
        }

        private bool SupplierContactExists(int id)
        {
            return _context.SupplierContacts.Any(e => e.Id == id);
        }

        // GET: Supplier/AddTransaction/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddTransaction(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var supplier = await _context.Suppliers.FindAsync(id);
            if (supplier == null)
            {
                return NotFound();
            }
            
            var viewModel = new SupplierTransactionViewModel
            {
                SupplierId = supplier.Id,
                SupplierName = supplier.Name,
                TransactionDate = DateTime.Now,
                TransactionNumber = GenerateTransactionNumber()
            };
            
            PrepareTransactionViewBags();
            return View(viewModel);
        }

        // POST: Supplier/AddTransaction
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> AddTransaction(SupplierTransactionViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var supplier = await _context.Suppliers.FindAsync(viewModel.SupplierId);
                    if (supplier == null)
                    {
                        return NotFound();
                    }

                    var transaction = new SupplierTransaction
                    {
                        SupplierId = viewModel.SupplierId,
                        TransactionNumber = viewModel.TransactionNumber,
                        TransactionDate = viewModel.TransactionDate,
                        Amount = viewModel.Amount,
                        TransactionType = viewModel.TransactionType,
                        PaymentMethod = viewModel.PaymentMethod,
                        PaymentStatus = viewModel.PaymentStatus,
                        Description = viewModel.Description,
                        CreatedAt = DateTime.Now
                    };
                    
                    _context.Add(transaction);
                    await _context.SaveChangesAsync();
                    
                    TempData["SuccessMessage"] = "交易记录添加成功！";
                    return RedirectToAction(nameof(Details), new { id = viewModel.SupplierId });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, $"添加交易记录失败: {ex.Message}");
                }
            }
            
            var supplierInfo = await _context.Suppliers.FindAsync(viewModel.SupplierId);
            if (supplierInfo != null)
            {
                viewModel.SupplierName = supplierInfo.Name;
            }
            
            PrepareTransactionViewBags();
            return View(viewModel);
        }

        // GET: Supplier/EditTransaction/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditTransaction(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var transaction = await _context.SupplierTransactions
                .Include(t => t.Supplier)
                .FirstOrDefaultAsync(t => t.Id == id);
                
            if (transaction == null)
            {
                return NotFound();
            }
            
            var viewModel = new SupplierTransactionViewModel
            {
                Id = transaction.Id,
                SupplierId = transaction.SupplierId,
                SupplierName = transaction.Supplier.Name,
                TransactionNumber = transaction.TransactionNumber,
                TransactionDate = transaction.TransactionDate,
                Amount = transaction.Amount,
                TransactionType = transaction.TransactionType,
                PaymentMethod = transaction.PaymentMethod,
                PaymentStatus = transaction.PaymentStatus,
                Description = transaction.Description
            };
            
            PrepareTransactionViewBags();
            return View(viewModel);
        }

        // POST: Supplier/EditTransaction/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> EditTransaction(int id, SupplierTransactionViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var transaction = await _context.SupplierTransactions.FindAsync(id);
                    if (transaction == null)
                    {
                        return NotFound();
                    }

                    // 更新交易记录信息
                    transaction.TransactionNumber = viewModel.TransactionNumber;
                    transaction.TransactionDate = viewModel.TransactionDate;
                    transaction.Amount = viewModel.Amount;
                    transaction.TransactionType = viewModel.TransactionType;
                    transaction.PaymentMethod = viewModel.PaymentMethod;
                    transaction.PaymentStatus = viewModel.PaymentStatus;
                    transaction.Description = viewModel.Description;
                    transaction.UpdatedAt = DateTime.Now;
                    
                    _context.Update(transaction);
                    await _context.SaveChangesAsync();
                    
                    TempData["SuccessMessage"] = "交易记录更新成功！";
                    return RedirectToAction(nameof(Details), new { id = transaction.SupplierId });
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SupplierTransactionExists(viewModel.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            
            var supplierInfo = await _context.Suppliers.FindAsync(viewModel.SupplierId);
            if (supplierInfo != null)
            {
                viewModel.SupplierName = supplierInfo.Name;
            }
            
            PrepareTransactionViewBags();
            return View(viewModel);
        }

        // GET: Supplier/DeleteTransaction/5
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteTransaction(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var transaction = await _context.SupplierTransactions
                .Include(t => t.Supplier)
                .FirstOrDefaultAsync(t => t.Id == id);
                
            if (transaction == null)
            {
                return NotFound();
            }

            return View(transaction);
        }

        // POST: Supplier/DeleteTransaction/5
        [HttpPost, ActionName("DeleteTransaction")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Administrator,Manager")]
        public async Task<IActionResult> DeleteTransactionConfirmed(int id)
        {
            var transaction = await _context.SupplierTransactions.FindAsync(id);
            if (transaction != null)
            {
                int supplierId = transaction.SupplierId;
                _context.SupplierTransactions.Remove(transaction);
                await _context.SaveChangesAsync();
                
                TempData["SuccessMessage"] = "交易记录已删除！";
                return RedirectToAction(nameof(Details), new { id = supplierId });
            }
            
            return RedirectToAction(nameof(Index));
        }

        private bool SupplierTransactionExists(int id)
        {
            return _context.SupplierTransactions.Any(e => e.Id == id);
        }
        
        private void PrepareTransactionViewBags()
        {
            ViewBag.TransactionTypes = new SelectList(Enum.GetValues(typeof(TransactionType))
                .Cast<TransactionType>()
                .Select(t => new { Id = (int)t, Name = GetEnumDisplayName(t) }),
                "Id", "Name");
                
            ViewBag.PaymentMethods = new SelectList(Enum.GetValues(typeof(PaymentMethod))
                .Cast<PaymentMethod>()
                .Select(m => new { Id = (int)m, Name = GetEnumDisplayName(m) }),
                "Id", "Name");
                
            ViewBag.PaymentStatuses = new SelectList(Enum.GetValues(typeof(PaymentStatus))
                .Cast<PaymentStatus>()
                .Select(s => new { Id = (int)s, Name = GetEnumDisplayName(s) }),
                "Id", "Name");
        }
        
        private string GenerateTransactionNumber()
        {
            // 生成一个交易编号，格式：SPTRAXXXXXXXX（SP供应商-TRA交易-年月日-4位随机数）
            string prefix = "SPTRA";
            string dateStr = DateTime.Now.ToString("yyyyMMdd");
            string randomStr = new Random().Next(1000, 9999).ToString();
            
            return $"{prefix}{dateStr}{randomStr}";
        }

        private string GetEnumDisplayName(Enum value)
        {
            var displayName = value.GetType()
                .GetMember(value.ToString())
                .FirstOrDefault()
                ?.GetCustomAttributes(typeof(DisplayAttribute), false)
                .OfType<DisplayAttribute>()
                .FirstOrDefault()
                ?.Name;

            return displayName ?? value.ToString();
        }
    }
} 